/**
 * 主菜单 - 主菜单导航
 * 
 * @author 艾格林门信息服务（大连）有限公司
 * @copyright 2015 - present
 * @license GPL v3
 */
PCL.define("PSI.MainMenu.MenuNavForm", {
  extend: "PSI.AFX.Form.EditForm",

  config: {
    mainMenuData: null,
  },

  /**
   * 初始化组件
   * 
   * @override
   */
  initComponent() {
    const me = this;

    const prodName = PSI.Const.PROD_NAME;

    const year = new Date().getFullYear();
    const c = `Copyright &copy; 2015-${year} 艾格林门信息服务（大连）有限公司, All Rights Reserved`;
    const logo = `${PSI.Const.BASE_URL}Public/Images/icons/psi_xl.png`;

    PCL.apply(me, {
      header: false,
      width: 900,
      height: 520,
      layout: "border",
      onEsc: me._onClose,
      closable: true,
      listeners: {
        show: {
          fn: me._onWndShow,
          scope: me
        },
      },
      items: [{
        region: "center",
        layout: "border",
        border: 0,
        items: [
          {
            region: "north",
            border: 0,
            id: me.buildId(me, "mainPanel"),
          },
          {
            region: "center",
            border: 0,
            html: `
              <img src="${logo}"
                style="margin-top: 30px;margin-right: 10px;margin-left:20px;width:32px;float:left" />
              <h1 style='color:#003a8c;margin-top:30px;margin-left:20px;padding-left:5px'>
                ${prodName} - 赋能企业信息化升级
              </h1>
              <h2 style="margin-left:20px;margin-top: 60px;color:#003a8c;padding-left: 5px;">
                管理就是界定企业的使命，并激励和组织人力资源去实现这个使命。界定使命是企业家的任务，而激励与组织人力资源是领导力的范畴，二者的结合就是管理。
              </h2>
              <div style="text-align: right;margin-right: 30px;color:#003a8c;">彼得·德鲁克</div>    
              <div style='margin-left:20px;margin-top:210px;font-size:14px'>
                <p>&nbsp;&nbsp;${c}</p>
              </div>
            `
          }
          , {
            region: "west",
            width: 200,
            border: 0,
            layout: "fit",
            items: me.getRecentGrid()
          }
        ]
      }],
      buttons: [{
        xtype: "displayfield", value: "ESC键关闭"
      }, "->", {
        text: "关闭",
        handler() {
          me.close();
        },
        scope: me
      }]
    });

    me.callParent(arguments);
  },

  /**
   * 常用功能Grid
   * 
   * @private
   */
  getRecentGrid() {
    const me = this;
    if (me._recentGrid) {
      return me._recentGrid;
    }

    const modelName = me.buildModelName(me, "FId");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["fid", "name"]
    });

    const storeRecentFid = PCL.create("PCL.data.Store", {
      autoLoad: false,
      model: modelName,
      data: []
    });

    me._recentGrid = PCL.create("PCL.grid.Panel", {
      header: {
        title: "常用功能",
        height: 28
      },
      border: 1,
      titleAlign: "center",
      cls: "PSI-recent-fid",
      forceFit: true,
      hideHeaders: true,
      columns: [{
        dataIndex: "name",
        menuDisabled: true,
        menuDisabled: true,
        sortable: false,
        width: 16,
        renderer(value, metaData, record) {
          const fid = record.get("fid");
          const getFileName = (fid) => {
            const isCodeTable = fid.substring(0, 2) == "ct";
            if (isCodeTable) {
              return "Public/Images/fid/fid_todo.png";
            }

            // TODO 还需要处理LCAP的其他模块

            return `Public/Images/fid/fid${fid}.png`;
          }

          const fileName = getFileName(fid);
          const url = me.URL(fileName);

          return `
          <a href='#' style='text-decoration:none'>
            <img src='${url}' style='vertical-align: middle;margin:0px 5px 0px 5px'></img>
          </a>
          `;
        }
      }, {
        dataIndex: "name",
        menuDisabled: true,
        menuDisabled: true,
        sortable: false,
        renderer(value, metaData, record) {
          return `
          <a href='#' style='text-decoration:none'>
            <span style='vertical-align: middle'>${value}</span>
          </a>
          `;
        }
      }],
      store: storeRecentFid
    });

    const theForm = me;
    me._recentGrid.on("cellclick", (me, td, cellIndex, r, tr, rowIndex, e, eOpts) => {
      theForm.close();

      const fid = r.get("fid");

      const url = `${PSI.Const.BASE_URL}Home/MainMenu/navigateTo/fid/${fid}/t/1`;

      if (fid === "-9999") {
        // TODO 在常用功能里面，应该是没有重新登录这项
        PSI.MsgBox.confirm("请确认是否重新登录", function () {
          location.replace(url);
        });
      } else {
        if (PSI.Const.MOT == "0") {
          // 模块打开方式：原窗口打开
          if (cellIndex == 2) {
            // 新窗口打开
            window.open(url);
            // 清除当前选中项，为了更好的视觉效果
            me.getSelectionModel().deselectAll();
          }
          else {
            location.replace(url);
          }
        } else {
          // 模块打开方式：新窗口打开
          window.open(url);
          // 清除当前选中项，为了更好的视觉效果
          me.getSelectionModel().deselectAll();
        }
      }
    }, me);

    return me._recentGrid;
  },

  /**
   * @private
   */
  _onWndShow() {
    const me = this;

    me.createMainMenu(me.getMainMenuData());

    // 查询常用功能数据
    const el = me.getRecentGrid().getEl();
    el && el.mask("系统正在加载中...");
    const store = me.getRecentGrid().getStore();
    store.removeAll();

    me.ajax({
      url: me.URL("Home/MainMenu/recentFid"),
      callback(opt, success, response) {
        if (success) {
          const data = me.decodeJSON(response.responseText);
          store.add(data);
        }
        el && el.unmask();
      },
      scope: me
    });

  },

  _onClose() {
    const me = this;
    me.close();
  },

  /**
   * 创建主菜单
   * 
   * @private 
   */
  createMainMenu(root) {
    const me = this;

    const menuItemClick = (item) => {
      me.close();

      const fid = item.fid;

      if (fid == "-9995") {
        window.open(me.URL("Home/Help/index"));
      } else if (fid === "-9999") {
        // 重新登录
        PSI.MsgBox.confirm(`请确认是否重新登录${PSI.Const.PROD_NAME} ?`, function () {
          location.replace(me.URL("Home/MainMenu/navigateTo/fid/-9999"));
        });
      } else {
        const url = me.URL(`Home/MainMenu/navigateTo/fid/${fid}`);
        if (PSI.Const.MOT == "0") {
          location.replace(url);
        } else {
          window.open(url);
        }
      }
    };

    const mainMenu = [];

    const getIconCls = (fid) => {
      const isCodeTable = fid.substring(0, 2) == "ct";
      if (isCodeTable) {
        return "PSI-fid_todo";
      }

      // TODO 还需要处理LCAP其他模块

      return `PSI-fid${fid}`;
    };

    root.forEach((m1) => {
      const menuItem = PCL.create("PCL.menu.Menu", { plain: true });
      m1.children.forEach((m2) => {
        if (m2.children.length === 0) {
          // 只有二级菜单
          if (m2.fid) {
            menuItem.add({
              text: m2.caption,
              fid: m2.fid,
              handler: menuItemClick,
              iconCls: getIconCls(m2.fid)
            });
          }
        } else {
          const menuItem2 = PCL.create("PCL.menu.Menu", { plain: true });

          menuItem.add({
            text: m2.caption,
            menu: menuItem2
          });

          // 三级菜单
          m2.children.forEach((m3) => {
            menuItem2.add({
              text: m3.caption,
              fid: m3.fid,
              handler: menuItemClick,
              iconCls: getIconCls(m3.fid)
            });
          });
        }
      });

      if (m1.children.length > 0) {
        mainMenu.push({
          text: m1.caption,
          menu: menuItem
        });
      }
    });

    const mainToolbar = PCL.create("PCL.toolbar.Toolbar", {
      border: 0,
      dock: "top"
    });
    mainToolbar.add(mainMenu);

    const theCmp = PCL.getCmp(me.buildId(me, "mainPanel"));

    theCmp.addTool(mainToolbar);
  },
});
